# -*- coding: utf-8 -*-
from flask import Blueprint, request, redirect, jsonify
from application import app, db
from common.libs.UrlManager import UrlManager
from common.libs.helper import ops_render, iPagination, getCurrentDate
from common.models.member.Member import Member

route_member = Blueprint('member_page', __name__)


@route_member.route("/index")
def index():
    context = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    query = Member.query

    if 'mix_kw' in req:
        query = query.filter(Member.nickname.ilike('%{0}%'.format(req['mix_kw'])))

    if 'status' in req and int(req['status']) > -1:
        query = query.filter_by(status=int(req['status']))

    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace('&p={}'.format(page), ''),
    }

    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']
    query_list = query.order_by(Member.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()

    context['list'] = query_list
    context['pages'] = pages
    context['search_con'] = req
    context['status_mapping'] = app.config['STATUS_MAPPING']
    context['current'] = 'index'
    return ops_render("member/index.html", context)


@route_member.route("/info")
def info():
    context = {}
    req = request.args
    id = int(req.get('id', 0))
    reback_url = UrlManager.buildUrl('/member/info.html')
    if id < 1:
        return redirect(reback_url)

    info = Member.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)

    context['info'] = info
    context['current'] = 'index'
    return ops_render("member/info.html", context)


@route_member.route("/set", methods=['GET','POST'])
def set():
    if request.method == 'GET':
        context = {}
        req = request.args
        id = int(req.get('id', 0))
        reback_url = UrlManager.buildUrl('/member/index')
        if id < 1:
            return redirect(reback_url)
        info = Member.query.filter_by(id=id).first()
        if not info:
            return redirect(reback_url)
        if info.status != 1:
            return redirect(reback_url)

        context['info'] = info
        context['current'] = 'index'

        return ops_render('/member/set.html', context)

    resp = {'code':200, 'msg':'操作成功~~', 'data':{}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else None
    if nickname is None or len(nickname) < 1:
        resp['code'] = 201
        resp['msg'] = '请输入正确的昵称'
        return jsonify(resp)

    mobile = req['mobile'] if 'mobile' in req else None
    print(mobile)
    if mobile is None or len(mobile) < 11:
        resp['code'] = 201
        resp['msg'] = '请输入正确的手机号'
        return jsonify(resp)

    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp['code'] = 202
        resp['msg'] = '指定会员不存在'
        return jsonify(resp)

    member_info.nickname = nickname
    member_info.mobile = mobile
    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()

    return jsonify(resp)


@route_member.route("/comment")
def comment():
    return ops_render("member/comment.html")


@route_member.route('/ops', methods=['POST'])
def ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = '请选择要操作的账号~~'
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = '操作有误，请重试~~'
        return jsonify(resp)

    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = '指定会员不存在~~'
        return jsonify(resp)
    if act == 'remove':
        member_info.status = 0
    elif act == 'recover':
        member_info.status = 1

    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()

    return jsonify(resp)